/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tencent.tendon.convert.json;

import java.lang.reflect.*;
import java.util.Collection;

/**
 *
 * @author nbzhang
 */
public class JsonCollectionEncoder<T> extends JsonEncoder<Collection<T>> {

    private final JsonEncodable<T> encoder;

    JsonCollectionEncoder(final Type type) {
        super(type);
        if (type instanceof ParameterizedType) {
            this.encoder = JsonLoader.loadEncodable(((ParameterizedType) type).getActualTypeArguments()[0]);
        } else {
            this.encoder = (JsonEncodable<T>) JsonAnyEncoder.getInstance();
        }
        this.simpled = encoder.isSimpled();
    }

    public JsonCollectionEncoder(final Class<Collection<T>> type, final JsonEncodable<T> encoder) {
        super(type);
        this.encoder = encoder;
        this.simpled = encoder.isSimpled();
    }

    @Override
    public void convertTo(JsonWriter out, Collection<T> value) {
        final Collection<T> values = value;
        if (values == null) {
            out.writeNull();
            return;
        }
        if (values.isEmpty()) {
            out.write('[', ']');
            return;
        }
        if (out.writeRefer(value)) return;
        if (!simpled) out.offer(value);
        out.write('[');
        boolean first = true;
        for (T v : value) {
            if (!first) out.write(',');
            encoder.convertTo(out, v);
            if (first) first = false;
        }
        out.write(']');
        if (!simpled) out.poll();
    }
}
